// 自动保存Hook
// 提供自动保存功能的React Hook

import { useEffect, useRef, useCallback } from 'react';
import { getAutoSaveService, AutoSaveConfig } from '../services/autoSaveService';
import { useTabStore } from '../stores/tabStore';

// Hook选项
export interface UseAutoSaveOptions {
  config?: Partial<AutoSaveConfig>;
  onSave?: (tabId: string, success: boolean) => void;
  onBackupCreated?: (tabId: string, backupId: string) => void;
  onSessionRecovered?: (tabCount: number) => void;
}

// Hook返回值
export interface UseAutoSaveReturn {
  isEnabled: boolean;
  config: AutoSaveConfig;
  updateConfig: (newConfig: Partial<AutoSaveConfig>) => void;
  saveNow: () => Promise<void>;
  createBackup: (tabId: string) => Promise<void>;
  restoreBackup: (tabId: string, backupId: string) => Promise<boolean>;
  getBackups: (tabId: string) => any[];
  saveSession: () => Promise<void>;
  recoverSession: () => Promise<boolean>;
  clearSession: () => void;
}

// 自动保存Hook
export const useAutoSave = (options: UseAutoSaveOptions = {}): UseAutoSaveReturn => {
  const { config, onSave, onBackupCreated, onSessionRecovered } = options;
  
  const serviceRef = useRef(getAutoSaveService(config));
  const { tabs, activeTabId, getModifiedTabs } = useTabStore();

  // 启动自动保存服务
  useEffect(() => {
    const service = serviceRef.current;
    service.start();

    return () => {
      service.stop();
    };
  }, []);

  // 监听标签页变化，触发会话保存
  useEffect(() => {
    const service = serviceRef.current;
    const saveSessionDebounced = debounce(() => {
      service.saveSession();
    }, 1000);

    saveSessionDebounced();
  }, [tabs, activeTabId]);

  // 立即保存所有修改的标签页
  const saveNow = useCallback(async () => {
    const modifiedTabs = getModifiedTabs();
    const results = await Promise.all(
      modifiedTabs.map(async (tab) => {
        try {
          // 这里应该调用实际的保存逻辑
          // 暂时使用tabStore的saveTab方法
          const tabStore = useTabStore.getState();
          const success = await tabStore.saveTab(tab.id);
          onSave?.(tab.id, success);
          return success;
        } catch (error) {
          onSave?.(tab.id, false);
          return false;
        }
      })
    );

    console.log(`Saved ${results.filter(Boolean).length}/${results.length} tabs`);
  }, [getModifiedTabs, onSave]);

  // 为指定标签页创建备份
  const createBackup = useCallback(async (tabId: string) => {
    const service = serviceRef.current;
    const tab = tabs.get(tabId);
    
    if (tab) {
      // 这里应该调用service的createBackup方法
      // 由于createBackup是私有方法，我们需要通过其他方式
      console.log(`Creating backup for tab: ${tabId}`);
      onBackupCreated?.(tabId, `backup_${Date.now()}`);
    }
  }, [tabs, onBackupCreated]);

  // 恢复备份
  const restoreBackup = useCallback(async (tabId: string, backupId: string) => {
    const service = serviceRef.current;
    const success = await service.restoreBackup(tabId, backupId);
    return success;
  }, []);

  // 获取备份列表
  const getBackups = useCallback((tabId: string) => {
    const service = serviceRef.current;
    return service.getBackups(tabId);
  }, []);

  // 保存会话
  const saveSession = useCallback(async () => {
    const service = serviceRef.current;
    await service.saveSession();
  }, []);

  // 恢复会话
  const recoverSession = useCallback(async () => {
    const service = serviceRef.current;
    const success = await service.recoverSession();
    
    if (success) {
      const tabCount = tabs.size;
      onSessionRecovered?.(tabCount);
    }
    
    return success;
  }, [tabs.size, onSessionRecovered]);

  // 清除会话
  const clearSession = useCallback(() => {
    const service = serviceRef.current;
    service.clearSession();
  }, []);

  // 更新配置
  const updateConfig = useCallback((newConfig: Partial<AutoSaveConfig>) => {
    const service = serviceRef.current;
    service.updateConfig(newConfig);
  }, []);

  return {
    isEnabled: serviceRef.current.getConfig().enabled,
    config: serviceRef.current.getConfig(),
    updateConfig,
    saveNow,
    createBackup,
    restoreBackup,
    getBackups,
    saveSession,
    recoverSession,
    clearSession,
  };
};

// 防抖函数
function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}
